package cn.wang.sms.mq;

import cn.wang.sms.config.ConfigProper;
import cn.wang.sms.utils.SmsUtil;
import com.alibaba.fastjson.JSON;
import com.aliyuncs.exceptions.ClientException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Map;

@Slf4j
@Component
public class SmsListener {
    @Autowired
    private SmsUtil smsUtil;

    @Autowired
    private ConfigProper proper;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "sms.verifier.code.queue", durable = "true"),
            exchange = @Exchange(name = "ly.sms.exchange", type = ExchangeTypes.TOPIC),
            key = "sms.register"
    ))
    public void sendVerifierCode(Map<String, String> msg) {
        if (CollectionUtils.isEmpty(msg)) {
            log.info("[短信微服务] 发送失败, 传递参数为空");
            return;
        }
        String phoneNumber = msg.remove("phoneNumber");
        if (StringUtils.isEmpty(phoneNumber)) {
            log.info("[短信微服务] 发送失败, 电话号码为空");
            return;
        }
        try {
            smsUtil.sendSms(phoneNumber, proper.getSignName(), proper.getVerifierCode(), JSON.toJSONString(msg));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
